package dao;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.*;


public class BaseDao {
 public Connection conn(){
     try {
         Class.forName("com.mysql.jdbc.Driver");
     }
     catch (Exception e) {
         e.printStackTrace();
     }
     Connection conn=null;
     try {
         conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/newsmanagersystem?useUnicode=true&characterEncoding=utf-8", "root", "Qq7788110");
         return conn;
     } catch (SQLException throwables) {
         throwables.printStackTrace();
     }
     return null;
 }

 public Connection getConnByJNDI(){
     Connection conn=null;
     try {
         Context context=new InitialContext();
         DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/news");
         conn=dataSource.getConnection();
         return conn;
     }catch (Exception e){
        e.printStackTrace();
     }
     return null;
 }

 public PreparedStatement pstmt(Connection conn,String sql,Object objs[]){

    PreparedStatement pstmt=null;
     try {
         pstmt=conn.prepareStatement(sql);
        if (objs!=null){
            for (int i=0;i<objs.length;i++){
                pstmt.setObject(i+1,objs[i]);
            }
        }
        return pstmt;
     } catch (SQLException throwables) {
         throwables.printStackTrace();
     }
     return null;
 }//查询用

 public int executeUpdate(Connection conn,String sql, Object [] objs) {
        PreparedStatement pstmt=null;
        try {
            pstmt=conn.prepareStatement(sql);
            //绑定参数
            if (objs!=null){
                for (int i=0;i<objs.length;i++){
                    pstmt.setObject(i+1,objs[i]);
                }
            }
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            cloesAll(conn,pstmt,null);
        }
        return 0;
    }//编辑用

    public void cloesAll(Connection conn, Statement stmt, ResultSet rs) {
        if (conn !=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt !=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs !=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
